package com.suneast.suneaststore.modules.homepage;

import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.homepage.BrandBean;
import com.suneast.suneaststore.bean.search.SearchBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.common.GlideImageLoader;
import com.suneast.suneaststore.modules.goodsdetail.GoodsDetailFragment;
import com.suneast.suneaststore.modules.homepage.adapter.BrandAdapter;
import com.suneast.suneaststore.modules.homepage.adapter.GoodsAdapter;
import com.suneast.suneaststore.modules.homepage.event.FilterSetEvent;
import com.suneast.suneaststore.modules.homepage.event.GotBrandList;
import com.suneast.suneaststore.modules.homepage.event.GotGoodsList;
import com.suneast.suneaststore.modules.homepage.event.GotHomePageData;
import com.suneast.suneaststore.modules.homepage.event.RequestResult;
import com.suneast.suneaststore.modules.personal.order.fragment.FastOrderMaker;
import com.suneast.suneaststore.modules.personal.sign.SignInFragment;
import com.suneast.suneaststore.modules.search.SearchFragment;
import com.suneast.suneaststore.modules.store.ExchangeStoreFragment;
import com.suneast.suneaststore.modules.store.StoreListFragment;
import com.suneast.suneaststore.ui.banner.Banner;
import com.suneast.suneaststore.ui.banner.BannerConfig;
import com.suneast.suneaststore.ui.fragments.bottom.BottomItemFragment;
import com.suneast.suneaststore.ui.pagergrid.PagerGridLayoutManager;
import com.suneast.suneaststore.ui.pagergrid.PagerGridSnapHelper;
import com.suneast.suneaststore.util.dimen.ScreenUtil;
import com.suneast.suneaststore.util.log.LatteLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

import static com.suneast.suneaststore.modules.search.SearchFragment.FILTERS;
import static com.suneast.suneaststore.modules.search.SearchFragment.MAX_PRICE;
import static com.suneast.suneaststore.modules.search.SearchFragment.MIN_PRICE;
import static com.suneast.suneaststore.modules.search.SearchFragment.ORDER;
import static com.suneast.suneaststore.modules.search.SearchFragment.PAGE;
import static com.suneast.suneaststore.modules.search.SearchFragment.SORT;

public class HomePageFragment extends BottomItemFragment implements RadioGroup.OnCheckedChangeListener {

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_home_page;
    }

    @BindView(R.id.banner)
    Banner banner = null;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.rg_target_filter)
    RadioGroup productFilterRG;

    @BindView(R.id.rg_cid_filter)
    RadioGroup brandFilterRG;

    @BindView(R.id.rv_brand)
    RecyclerView brandRV;
    PagerGridLayoutManager pagerGridLayoutManager;
    BrandAdapter brandAdapter;
    private TextView lastTv;

    @BindView(R.id.rg_indicator)
    RadioGroup indicatorRG;

    @BindView(R.id.rg_sort_filter)
    RadioGroup sortFilterRG;

    @BindView(R.id.rv_product)
    RecyclerView productRV;
    GoodsAdapter goodsAdapter;

    @BindViews({R.id.rb_mp, R.id.rb_jp, R.id.rb_tj})
    RadioButton[] radioButtons;
    @BindView(R.id.btn_dh)
    Button dhBtn;

    @BindView(R.id.rb_jp)
    RadioButton jpRb;

    @BindView(R.id.rb_finished_product)
    RadioButton finishedProductRb;

    @BindView(R.id.rb_synthesize)
    RadioButton synthesizeRb;

    @OnClick({R.id.tv_search, R.id.btn_search, R.id.btn_dh, R.id.btn_store,
            R.id.btn_customization, R.id.btn_show_filter})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
            case R.id.btn_search: {
                getParentDelegate().start(new SearchFragment());
            }
            break;
            case R.id.btn_dh: {
                getParentDelegate().start(new ExchangeStoreFragment());
            }
            break;
            case R.id.btn_store: {
                getParentDelegate().start(new StoreListFragment());
            }
            break;
            case R.id.btn_customization: {
                // show fastOrderMaker
//                if (AccountManager.getSignState()) {
                    getParentDelegate().start(new FastOrderMaker());
//                } else {
//                    getParentDelegate().start(new SignInFragment());
//                }
//                start(new H5PayTestFragment());
            }
            break;
            case R.id.btn_show_filter: {
                //show filterFragment
                getParentDelegate().start(new FilterFragment().withId(
                        brandFilterRG.getCheckedRadioButtonId() == R.id.rb_finished_product ? Flag.Cid.FINISHED_PRODUCT : Flag.Cid.MATERIALS)
                );
            }
            break;
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initData();
        initView();
        HomePageHandler.requestHomePage();
    }

    private @Flag.Target
    int curTarget;
    private @Flag.Cid
    int curCid;
    private ArrayList<RadioButton> indicatorArray;
    private WeakHashMap<String, Object> paramsMap;

    private void initData() {
        indicatorArray = new ArrayList<>();
        curTarget = Flag.Target.JP;
        curCid = Flag.Cid.FINISHED_PRODUCT;
        paramsMap = new WeakHashMap<>();
        paramsMap.put("target", curTarget);
        paramsMap.put("cid", curCid);
        paramsMap.put("page", curPage);
        paramsMap.put("psize", 12);
    }

    private void initView() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.isAutoPlay(true);
        banner.setDelayTime(5000);
        banner.setIndicatorGravity(BannerConfig.BOTTOM_CENTER);

        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener((@NonNull RefreshLayout refreshLayout) -> {
            LatteLogger.e("test", "onRefresh");
            resetHomePage();
        });

        refreshLayout.setOnLoadMoreListener((@NonNull RefreshLayout refreshLayout) -> {
            paramsMap.put("page", curPage + 1);
            HomePageHandler.requestGoodsList(paramsMap);
        });

        for (RadioButton rb : radioButtons) reSizeDrawTop(rb);
        reSizeDrawTop(dhBtn);

        productFilterRG.setOnCheckedChangeListener(this);
        brandFilterRG.setOnCheckedChangeListener(this);
        sortFilterRG.setOnCheckedChangeListener(this);

        pagerGridLayoutManager =
                new PagerGridLayoutManager(2, 4, PagerGridLayoutManager.HORIZONTAL);
        pagerGridLayoutManager.setChangeSelectInScrolling(false);
        pagerGridLayoutManager.setPageListener(new PagerGridLayoutManager.PageListener() {
            @Override
            public void onPageSizeChanged(int pageSize) {
                Log.e(TAG, "onPageSizeChanged: pageSize = " + pageSize);
                if (pageSize > 0) {
                    setIndicator(pageSize);
                }
            }

            @Override
            public void onPageSelect(int pageIndex) {
                Log.e(TAG, "onPageSelect: pageIndex = " + pageIndex);
                if (indicatorArray.size() > 0) {//!scrolling &&
                    RadioButton btn = indicatorArray.get(pageIndex);
                    btn.setChecked(true);
                }
            }
        });
        brandRV.setLayoutManager(pagerGridLayoutManager);

        PagerGridSnapHelper snapHelper = new PagerGridSnapHelper();
        snapHelper.attachToRecyclerView(brandRV);
        brandAdapter = new BrandAdapter(R.layout.item_product_store_category);
        brandAdapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            if (lastTv != null) {
                lastTv.setTextColor(Color.BLACK);
            }
            lastTv = view.findViewById(R.id.tv_category_name);
            lastTv.setTextColor(Color.RED);
            shouldReplace = true;
            BrandBean bean = (BrandBean) adapter.getData().get(position);
            LatteLogger.e("test", "brandId = " + bean.getId());
            paramsMap.put("brand", bean.getId());
            HomePageHandler.requestGoodsList(paramsMap);
        });
        brandRV.setAdapter(brandAdapter);

        initIndicator();

        productRV.setLayoutManager(new GridLayoutManager(getContext(), 2));
        goodsAdapter = new GoodsAdapter(R.layout.item_star_product);
        goodsAdapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            SearchBean bean = (SearchBean) adapter.getData().get(position);
            GoodsDetailFragment fragment = new GoodsDetailFragment().withId(bean.getId());
            getParentDelegate().start(fragment);
        });
        productRV.setAdapter(goodsAdapter);
    }

    private void resetHomePage() {
        paramsMap.clear();
        curTarget = Flag.Target.JP;
        curCid = Flag.Cid.FINISHED_PRODUCT;
        curPage = 0;
        paramsMap.put("target", curTarget);
        paramsMap.put("cid", curCid);
        paramsMap.put("page", curPage);
        paramsMap.put("psize", 12);
        jpRb.setChecked(true);
        finishedProductRb.setChecked(true);
        synthesizeRb.setChecked(true);
        HomePageHandler.requestHomePage();
    }

    private void reSizeDrawTop(Button btn) {
        Drawable[] drawables = btn.getCompoundDrawables();
        //获取drawables
        Rect r = new Rect(0, 0, drawables[1].getMinimumWidth() * 7 / 4,
                drawables[1].getMinimumHeight() * 7 / 4);
        //定义一个Rect边界
        drawables[1].setBounds(r);
        //添加限制给控件
        btn.setCompoundDrawables(null, drawables[1], null, null);
    }

    private final int MAX_NUM = 10;

    private void initIndicator() {
        int padding = ScreenUtil.dip2px(_mActivity, 8f);
        int margin = ScreenUtil.dip2px(_mActivity, 4f);
        for (int i = 0; i < MAX_NUM; i++) {
            RadioButton radioButton = new RadioButton(getContext());
            radioButton.setBackgroundResource(R.drawable.selector_indicator);//设置RadioButton的背景图片
            radioButton.setButtonDrawable(0);//取消圆圈
            radioButton.setPadding(padding, 0, 0, 0);
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(margin, 0, margin, 0);//设置边距
            radioButton.setTag(i);
            indicatorRG.addView(radioButton, lp);
            radioButton.setVisibility(View.GONE);
            if (i == 0) {
                indicatorRG.check(radioButton.getId());
            }
            indicatorArray.add(radioButton);
        }
        indicatorRG.setOnCheckedChangeListener((RadioGroup radioGroup, int checkedId) -> {
            RadioButton btn = radioGroup.findViewById(checkedId);
            int tag = (int) btn.getTag();
            Log.e(TAG, "setIndicator: tag = " + tag);
            pagerGridLayoutManager.smoothScrollToPage(tag);
        });
    }

    private void setIndicator(int size) {
        for (int i = 0; i < MAX_NUM; i++) {
            if (i < size) {
                indicatorArray.get(i).setVisibility(View.VISIBLE);
            } else {
                indicatorArray.get(i).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    GotHomePageData homePageData;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotHomePageData(GotHomePageData event) {
        homePageData = event;
        banner.setImages(event.getBanners());
        banner.start();
        brandAdapter.setNewData(event.getBrandBeans());
        goodsAdapter.setNewData(event.getGoodsBeans());
        refreshLayout.finishRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotBrandList(GotBrandList event) {
        brandAdapter.setNewData(event.getList());
        if (event.getList().size() == 0) {
            Toast.makeText(_mActivity, "此分类暂无品牌", Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotGoodsList(GotGoodsList event) {
        if (!event.isNoMoreData()) {
            if (shouldReplace) {
                goodsAdapter.setNewData(event.getGoodsList());
                shouldReplace = false;
            } else {
                goodsAdapter.addData(event.getGoodsList());
                curPage++;
            }
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.setNoMoreData(true);
        }
    }

    //处理各个请求失败的情况
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRequestResult(RequestResult event) {
        if (event.getResult() == Flag.Result.FAILURE) {
            switch (event.getType()) {
                case RequestResult.HOME_PAGE: {
                    refreshLayout.finishRefresh(false);
                }
                break;
                case RequestResult.BRAND_LIST: {
                    Toast.makeText(_mActivity, "品牌列表请求失败", Toast.LENGTH_SHORT).show();
                }
                break;
                case RequestResult.GOODS_LIST: {
                    Toast.makeText(_mActivity, "商品列表请求失败", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

    private void recoverLastTv() {
        if (lastTv != null) {
            lastTv.setTextColor(Color.BLACK);
            lastTv = null;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (radioGroup.getId()) {
            case R.id.rg_target_filter: {
                switch (checkedId) {
                    case R.id.rb_mp: {
                        curTarget = Flag.Target.MP;
                    }
                    break;
                    case R.id.rb_jp: {
                        curTarget = Flag.Target.JP;
                    }
                    break;
                    case R.id.rb_tj: {
                        curTarget = Flag.Target.TJ;
                    }
                    break;
                }
                recoverLastTv();
                HomePageHandler.requestBrandList(curTarget, curCid);
                paramsMap.remove("brand");
                paramsMap.put("target", curTarget);
                // 请求 goodslist
                if (synthesizeRb.isChecked()) {
                    paramsMap.put(ORDER, SearchFragment.order.id);
                    paramsMap.put(SORT, SearchFragment.sort.desc);
                    resetPage();
                    shouldReplace = true;
                    HomePageHandler.requestGoodsList(paramsMap);
                } else {
                    sortFilterRG.check(R.id.rb_synthesize);
                }
            }
            break;
            case R.id.rg_cid_filter: {
                switch (checkedId) {
                    case R.id.rb_finished_product: {
                        curCid = Flag.Cid.FINISHED_PRODUCT;
                    }
                    break;
                    case R.id.rb_materials: {
                        curCid = Flag.Cid.MATERIALS;
                    }
                    break;
                }
                recoverLastTv();
                HomePageHandler.requestBrandList(curTarget, curCid);
                paramsMap.remove("brand");
                paramsMap.put("cid", curCid);
                // 请求 goodslist
                if (synthesizeRb.isChecked()) {
                    paramsMap.put(ORDER, SearchFragment.order.id);
                    paramsMap.put(SORT, SearchFragment.sort.desc);
                    shouldReplace = true;
                    resetPage();
                    HomePageHandler.requestGoodsList(paramsMap);
                } else {
                    sortFilterRG.check(R.id.rb_synthesize);
                }
            }
            break;
            case R.id.rg_sort_filter: {
                shouldReplace = true;
                curPage = 0;
                paramsMap.put("page", curPage + 1);
                switch (checkedId) {
                    case R.id.rb_synthesize: {
                        paramsMap.put(ORDER, SearchFragment.order.id);
                        paramsMap.put(SORT, SearchFragment.sort.desc);
                    }
                    break;
                    case R.id.rb_sales: {
                        paramsMap.put(ORDER, SearchFragment.order.salesReal);
                        paramsMap.put(SORT, SearchFragment.sort.desc);
                    }
                    break;
                    case R.id.rb_price: {
                        paramsMap.put(ORDER, SearchFragment.order.memberPrice);
                        paramsMap.put(SORT, SearchFragment.sort.desc);
                    }
                    break;
                    case R.id.rb_good_reputation: {
                        paramsMap.put(ORDER, SearchFragment.order.comment);
                        paramsMap.put(SORT, SearchFragment.sort.desc);
                    }
                    break;
                }
                resetPage();
                HomePageHandler.requestGoodsList(paramsMap);
            }
            break;
        }
    }

    private boolean shouldReplace = false;
    private int curPage = 0;

    private void resetPage() {
        curPage = 1;
        paramsMap.put(PAGE, curPage);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotFilterSetEvent(FilterSetEvent event) {
        if (event.isReset()) {
            resetHomePage();
        } else {
            paramsMap.put(FILTERS, event.getFilterStrList());
            resetPage();
            paramsMap.put(MIN_PRICE, event.getMinPrice());
            paramsMap.put(MAX_PRICE, event.getMaxPrice());
            HomePageHandler.requestGoodsList(paramsMap);
        }
    }
}
